package com.qdu.util;

import com.qdu.exception.HouseException;
import org.springframework.util.CollectionUtils;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Set;


public class ValidationUtil {
    private static final Validator validator;
    static {
        ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
        validator = validatorFactory.getValidator();
    }
    public static void validateObject(Object obj){
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(obj);

        if(!CollectionUtils.isEmpty(constraintViolations)){
            StringBuffer errBuf = new StringBuffer();
            for (ConstraintViolation constraint:constraintViolations){
                String message = constraint.getMessage();
                errBuf.append(message).append(";");
            }
            throw new HouseException(errBuf.toString());
        }
    }
}
